#!/bin/sh /etc/rc.common
# Copyright (C) 2018-2019 Lienol <lawlienol@gmail.com>

START=99

CONFIG=v2ray_server
CONFIG_PATH=/var/etc/$CONFIG

gen_v2ray_config_file() {
	config_get enable $1 enable
	[ "$enable" = "0" ] && return 0
	config_get remarks $1 remarks
	config_get port $1 port
	lua /usr/lib/lua/luci/model/cbi/v2ray_server/api/genv2rayconfig.lua $1 > $CONFIG_PATH/$1.json
	/usr/bin/v2ray/v2ray -config $CONFIG_PATH/$1.json >/dev/null 2>&1 &
}

start_v2ray_server() {
	config_foreach gen_v2ray_config_file "user"
	fw3 reload
}

stop_v2ray_server() {
	fw3 reload
	ps -w | grep "$CONFIG_PATH/" | grep -v "grep" | awk '{print $1}' | xargs kill -9 >/dev/null 2>&1 &
}

start() {
	config_load $CONFIG
	enable=$(uci get $CONFIG.@global[0].enable)
	if [ "$enable" = "0" ];then
		stop_v2ray_server
	else
		mkdir -p $CONFIG_PATH
		start_v2ray_server
	fi
}

stop() {
	stop_v2ray_server
	rm -rf $CONFIG_PATH
}

restart() {
	stop
	sleep 1
	start
}